package com.ruoyi.system.pool;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @description: ssh
 * @author: stone
 * @date: Created by 2022/4/9 11:41
 * @version: 1.0.0
 * @pakeage: com.ruoyi.framework.config
 */
//@Component
public class SSHClient {

    /**
     * timeout for session connection
     */
    private final Integer SESSION_TIMEOUT = 60000;
    /**
     * timeout for channel connection
     */
    private final Integer CHANNEL_TIMEOUT = 60000;
    /**
     * the interval for acquiring ret
     */
    private final Integer CYCLE_TIME = 100;
    private String host = "localhost";
    /**
     * Server SSH Port，default value is 22
     */
    private Integer port = 22;
    /**
     * SSH Login Username
     */
    private String username = "";
    /**
     * SSH Login Password
     */
    private String password = "";
    private JSch jsch;
    private Session session = null;
    private Channel channel = null;


    public SSHClient() throws JSchException {
        // initialize
        jsch = new JSch();
        //jsch.addIdentity(pubKeyPath);
    }

    public static void main(String[] args) throws Exception {
        SSHClient sshClient = new SSHClient();
        sshClient.setPassword("123456");
        sshClient.login("root", "123.57.157.229", 8044);


        String cmd = sshClient.sendCmd("ps -ef |grep java");
        System.out.println(cmd);
        sshClient.logout();

    }

    public void login(String username, String host, Integer port) {
        this.username = username;
        this.host = host;
        this.port = port;
        //我的是免密登录，所以不用密码
//        this.password = password;

        try {
            if (null == session) {
                session = jsch.getSession(this.username, this.host, this.port);
                session.setPassword(this.password);
//                session.setUserInfo(new MyUserInfo());

                // It must not be recommended, but if you want to skip host-key check,
                // invoke following,
                session.setConfig("StrictHostKeyChecking", "no");
            }
            session.connect(SESSION_TIMEOUT);
        } catch (JSchException e) {
            this.logout();
        }
    }

    public void logout() {
        this.session.disconnect();
    }

    public void login() {
        this.login(this.username, this.host, this.port);
    }

    public synchronized String sendCmd(String command) throws Exception {

        // judge whether the session or channel is connected
        if (!session.isConnected()) {
            this.login();
        }
        if (this.session == null)
            return null;
        Channel channel = null;
        //InputStream input = null;
        BufferedReader bufferedReader = null;
        String resp = "";
        try {
            channel = this.session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);
            channel.connect();

            bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream()));

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                resp += line + "\n";
            }
            if (resp != null && !resp.equals("")) {
                resp = resp.substring(0, resp.length() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();

            throw e;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
        return resp;
    }


    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public JSch getJsch() {
        return jsch;
    }

    public void setJsch(JSch jsch) {
        this.jsch = jsch;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }
}
